package org.lewis.demo.util;

import com.fasterxml.jackson.databind.JsonNode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;
import org.springframework.web.reactive.function.client.WebClient;
import reactor.core.publisher.Mono;

import java.util.Map;

@Slf4j
@Component
public class ApiUtil {

    @Value("${keys.member.private-key}")
    private String privateKey;
    private final ParamUtil paramUtil;
    private final RsaUtil rsaUtil;
    private final WebClient webClient = WebClient.create();

    public ApiUtil(ParamUtil paramUtil, RsaUtil rsaUtil) {
        this.paramUtil = paramUtil;
        this.rsaUtil = rsaUtil;
    }

    public JsonNode post(String url, Map<String, Object> param) throws Exception {
        String sorted = this.paramUtil.values("", param);
        String sign = this.rsaUtil.md5Sign(sorted, this.privateKey);
        param.put("sign", sign);
        log.info("Post[url, param, sorted]: {}, {}, {}", url, param, sorted);

        Mono<JsonNode> mono = this.webClient.post().uri(url)
                .header("token", "token--- ---token--- ---token--- ---token")
                .contentType(MediaType.APPLICATION_JSON)
                .bodyValue(param)
                .retrieve().bodyToMono(JsonNode.class);
        return mono.block();
    }

}
